<template>
  <view class="img-container" :style="listHeightStylePage">
    <up-navbar title="查看图片" @leftClick="imgshowclose" placeholder></up-navbar>
    <view style="padding-right: 20rpx;padding-left: 20rpx;padding-top: 20rpx;padding-bottom: 20rpx;">
      <scroll-view  :refresher-background="'transparent'" class="img-list" :style="listHeightStyle" scroll-y="true" :refresher-enabled="true"
                   :refresher-triggered="isRefreshing" @refresherrefresh="onRefresh" @scrolltolower="loadMore">
        <view v-for="(img, index) in searchResults" :key="index" class="img-item">
          <!-- 头像和发送人 -->
          <view class="img-header">
            <view class="img-avatar">
              <image v-if="img.avatar" :src="img.avatar" class="avatar-circle"></image>
              <view v-else class="avatar-circle">{{ showUserName(img.username) }}</view>
            </view>
            <view class="img-sender">
              <text class="sender-name">{{ img.username }}</text>
            </view>
			<view>
			  <text style="font-size: 24rpx;color: #999;position: relative;top: -18rpx" class="sender-time">{{ img.sendtime }}</text>
			</view>
          </view>

          <!-- 图片展示  @click="previewImage()"-->
          <view class="img-content">
            <!-- 图片消息 -->
            <template v-if="img.type === 'img'">
              <up-parse :content="img.content"></up-parse>
            </template>

            <!-- 图片消息 -->
            <template v-else-if="img.type === 'img/text'">
              <up-parse :content="img.content"></up-parse>
            </template>
          </view>
        </view>

        <view v-if="searchResults.length === 0" class="no-img">
          <text>暂无图片</text>
        </view>

        <!-- 加载中提示 -->
        <view v-if="loading" class="loading-text">
          加载中...
        </view>

        <!-- 没有更多数据提示 -->
        <view v-if="noMore" class="no-more-text">
          没有更多数据了
        </view>
      </scroll-view>

    </view>
  </view>
</template>


<script>
import { chatApi } from '@/apis/cloud/chat';
import { useChatStore, useGroupStore, useUserStore } from '@/pinia-store/user';
import { processImageUrl } from "@/utils/chat";
import { mapStores } from 'pinia';

import graceRichText from "@/pages/chat/message/config/rich-text-format";
export default {
  name: "Groupchatpictures",
  components: {
 
  },
  data(){
    return{
      imgs:[],
      friend:null,
      imInfo:null,
      userInfo:null,
      dialogId:null,
      imgList:[],
      listHeight: 0, // 动态计算的高度
      listHeightStyle: {}, // 动态计算的样式
      topHeight: 0,
      listHeightStylePage: {},
      searchResults:[],
      Chatarray:[],
      isRefreshing: false,
      page:1,
      loading: false,
      noMore: false,
    }
  },
  computed: {
    ...mapStores(useChatStore, useUserStore, useGroupStore),
  },
  onLoad() {
    this.imInfo = this.chatStore.imInfo;// 当前登录用户
    this.userInfo = this.userStore.user;
    this.infoId = this.chatStore.imInfo.id
    this.group = this.groupStore.group;
    this.Getxiaoxi()
  },
  created(){
    // #ifdef H5
    this.listHeightStylePage = {
      height: `${window.innerHeight}px`,
    };
    // #endif

    // #ifdef APP-PLUS
    const res = uni.getSystemInfoSync();
    this.listHeight = res.windowHeight;
    this.listHeightStylePage = {
      height: `${res.windowHeight}px`,
    };

    // #endif
    this.calculateListHeight()
  },
  methods: {
    calculateListHeight() {
      const windowHeight = window.innerHeight; // 视口高度
      const topHeight = this.topHeight || 0; // 顶部安全高度
      const navbarHeight = 41; // 导航栏高度（假设为 44px）
      const tabsHeight = 23;
      // #ifdef APP-PLUS
      this.listHeightStyle = {
        overflowY: 'hidden',
        height: `${this.listHeight -95}px`,
      };
      // #endif

      // #ifdef H5
      const listHeight = windowHeight - topHeight - navbarHeight - tabsHeight;
      this.listHeightStyle = {
        height: `${listHeight}px`,
        overflowY: 'hidden',

      };
      // #endif
    },
    imgshowclose(){
      uni.navigateBack();
    },
    // 名称超长处理
    showUserName(username) {
      if (username && username.length > 2) {
        return username.substr(1, 2);
      } else {
        return username;
      }
    },
    // 预览图片
    onPreview(url) {
      const processedUrl = processImageUrl(url); // 使用统一处理方法
      this.imgs = [processedUrl];
      uni.previewImage({
        current: 0,
        urls: imgs,
      })
    },
    processAllMessages() {
      return this.Chatarray.reduce((result, item) => {

        try {
          if(item.status == 12){
            return  result
          }
          const parsedContent = JSON.parse(item.content);
          if (!Array.isArray(parsedContent)) return result;

          const processedMessages = parsedContent.map(msg => {
            // 过滤掉空内容的消息
            if (!msg.content || (typeof msg.content === 'string' && !msg.content.trim())) {
              return null;
            }

            const baseData = {
              fromname: item.fromname,
              toname: item.to_name,
              sendtime: item.send_time,
              username: item.username,
              avatar: item.avatar
            };

            switch (msg.type) {
              case 'img':
                return {
                  ...baseData,
                  type: 'img',
                  content: this.setImgUrl(msg.content),
                  rawContent: msg.content
                };
              case 'img/text':
                return {
                  ...baseData,
                  type: 'img/text',
                  content: this.setHtmlContent(msg.content),
                  rawContent: msg.content
                };
              default:
                return null;
            }
          }).filter(Boolean);

          return result.concat(processedMessages);
        } catch (e) {
          console.error('消息处理错误:', e, item);
          return result;
        }
      }, []);
    },
    // 处理图片链接为富文本
    setImgUrl (content) {
      if (this.isRichText(content))  {
        return graceRichText.format(content); 
      } else {
        // 处理图片URL 
        let processedUrl = content;
        
        // 处理没有域名的相对路径（以/uploads/开头）
        if (processedUrl.startsWith('/uploads/'))  {
          processedUrl = 'https://chat.mfarmers.com:88'  + processedUrl;
        } else if(processedUrl.startsWith('uploads/')){
          processedUrl = 'https://chat.mfarmers.com:88/'  + processedUrl;
        }
        
        // 处理有域名但端口是81的 
        processedUrl = processedUrl.replace('http://chat.mfarmers.com:81/',  'https://chat.mfarmers.com:88/'); 
        
        // 处理有域名但没有端口的
        processedUrl = processedUrl.replace('http://chat.mfarmers.com/',  'https://chat.mfarmers.com:88/'); 
        
        // 移除thumb_前缀（如果存在）
        processedUrl = processedUrl.replace(/(\/)thumb_/g,  '$1');
        
        // 确保URL使用HTTPS协议 
        if (processedUrl.startsWith('http://'))  {
          processedUrl = processedUrl.replace('http://',  'https://');
        }
        // 添加自适应样式
        return graceRichText.format(`<p><img  src="${processedUrl}" style="max-width: 200rpx; height: auto;" /></p>`);
      }
    },
    // 判断是否为富文本
    isRichText (str) {
      return /<[a-z][\s\S]*>/i.test(str);
    },
    setHtmlContent(content) {
      try {
        // 处理图片URL
        let processedContent = content;
        
        // 处理没有域名的相对路径（以/uploads/或uploads/开头）
        processedContent = processedContent.replace(/(src=")(uploads\/)/g,  '$1https://chat.mfarmers.com:88/$2'); 
        processedContent = processedContent.replace(/(src=")(\/uploads\/)/g,  '$1https://chat.mfarmers.com:88$2'); 
        
        // 处理有域名但端口是81的
        processedContent = processedContent.replace(/http:\/\/chat\.mfarmers\.com:81\//g,  'https://chat.mfarmers.com:88/'); 
        
        // 处理有域名但没有端口的 
        processedContent = processedContent.replace(/http:\/\/chat\.mfarmers\.com\//g,  'https://chat.mfarmers.com:88/'); 
        
        // 移除thumb_前缀（如果存在）
        processedContent = processedContent.replace(/(\/)thumb_/g,  '$1');
        
        // 提取所有图片URL
        const imgTags = processedContent.match(/<img[^>]+>/g)  || [];
    
        // 为每个图片添加自适应样式
        for (const imgTag of imgTags) {
          const newImgTag = imgTag.replace( 
            /(<img[^>]*)(>)/,
            '$1 style="max-width: 200rpx; height: auto;"$2'
          );
          processedContent = processedContent.replace(imgTag,  newImgTag);
        }
        // console.log('processedContent',processedContent);
        
        // 使用graceRichText格式化
        return graceRichText.format(processedContent); 
      } catch (e) {
        console.error(' 处理富文本内容失败:', e);
        return graceRichText.format(content); 
      }
    },
    async onRefresh() {
      this.isRefreshing = true; // 开始刷新
      this.Chatarray = [];
      this.page = 1;
      this.noMore = false;
      await this.Getxiaoxi();

    },
    async loadMore() {
      if (this.loading || this.noMore) return;
      this.page++;
      await this.Getxiaoxi();
    },
    // 获取消息记录
    async Getxiaoxi() {
      if (this.loading) {
        return
      }

      this.loading = true;
      uni.showLoading({
        title: '加载中....'
      });
      const params = {
        'data[groupId]': this.group.group_id,
        'data[account]': this.imInfo.account,
        'data[token]': this.userInfo.token,
        'data[myAccount]': this.imInfo.account,
        'data[page]': this.page,
        'data[pageSize]': 100,
        url: 'index.php/users/Group/getGroupChatRecord'
      }

      const msg = await chatApi(this.userInfo.token, params);

      if (msg.code == 200) {

        this.Chatarray = this.page == 1 ? msg.data.reverse() :  [...this.Chatarray, ...msg.data.reverse()];

        if(msg.data.length == 0){
          this.noMore = true;
        }
        this.isRefreshing = false;
        this.loading = false;
        uni.hideLoading();


        this.searchResults = this.processAllMessages();
      }else{
        this.loading = false;
        this.noMore = true;
        this.isRefreshing = false;
        uni.hideLoading();
      }
      uni.hideLoading();
    },
  },
}
</script>


<style scoped lang="scss">
.loading-text,
.no-more-text {
  margin-top: 20rpx;
  text-align: center;
  padding: 20rpx;
  color: #999;
  font-size: 28rpx;
}
// 查看图片弹窗
.img-container {
  width: 100vw;
  background-color: #f3f3f3;
  overflow-y: hidden;
  .img-list {
    overflow-y: auto;
    height: 93vh;

    .img-item {
      background-color: #ffffff;
      border-radius: 20rpx;
      padding: 20rpx;
      margin-bottom: 20rpx;

      .img-header {
        display: flex;
        align-items: center;

        .img-avatar {
          margin-right: 20rpx;

          .avatar-circle {
            width: 80rpx;
            height: 80rpx;
            border-radius: 15%;
            background-color: #377fff;
            color: #fff;
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 32rpx;
            font-weight: bold;
          }
        }

        .img-sender {
          flex: 1;
          display: flex;
          flex-direction: column;

          .sender-name {
            font-size: 28rpx;
            color: #333;
            font-weight: bold;
            margin-bottom: 30rpx;
          }

          .sender-time {
            font-size: 22rpx;
            color: #999;
          }
        }
      }
    }

    .no-img {
      text-align: center;
      padding: 40rpx 0;
      color: #999;
      font-size: 26rpx;
    }
  }
}

// 图片预览
.preview-container {
  position: relative;
  background-color: #000;

  .preview-item {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;
  }

  .preview-indicator {
    position: absolute;
    bottom: 50rpx;
    left: 0;
    right: 0;
    text-align: center;
    color: #fff;
    font-size: 28rpx;
    background-color: rgba(0, 0, 0, 0.5);
    padding: 10rpx 0;
    border-radius: 20rpx;
    width: 120rpx;
    margin: 0 auto;
  }
}

.img-content{
  text-align: center;
}
</style>
